﻿using System;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using CodeGeneration.Util;
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using RazorEngine.Text;
using Encoding = System.Text.Encoding;

namespace CodeGeneration.TextEngine
{
    public class RazorTextEngine:ITextEngine
    {
        public RazorTextEngine()
        {
            var config = new TemplateServiceConfiguration
            {
                Language = Language.CSharp,
                EncodedStringFactory = new RawStringFactory(),
                //EncodedStringFactory = new HtmlEncodedStringFactory(),
                //Debug = true,
                DisableTempFileLocking = true,
            };
            var service = RazorEngineService.Create(config);
            Engine.Razor = service;
        }
        public void TransferText<T>(T model, string file)
        {
            var name = typeof(T).Name.ToLower();
            name = name.Substring(0, name.LastIndexOf("model", StringComparison.Ordinal));
            var template = GetTemplateText($"{name}.cshtml");

            var result = Engine.Razor.RunCompile(template, name, typeof(T), model);

            TemplateUtil.RenderStringToFile(result, file);
        }

        public string GetTemplateText(string file)
        {
            var rootDir = Environment.CurrentDirectory;
            var path = Path.Combine(rootDir, "Template\\Razor", file);
            return File.ReadAllText(path, Encoding.UTF8);
        }
    }
}